import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import router from '@/router'
import { refreshToken as refreshTokenApi } from './auth'

// 创建axios实例
const request = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000/api/v1',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    console.log('发送请求:', config.method?.toUpperCase(), config.url, config.params)

    // 添加token到请求头（如果有的话）
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }

    return config
  },
  (error) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 是否正在刷新token
let isRefreshing = false
// 失败请求队列
let failedQueue = []

// 处理队列中的请求
const processQueue = (error, token = null) => {
  failedQueue.forEach(({ resolve, reject }) => {
    if (error) {
      reject(error)
    } else {
      resolve(token)
    }
  })

  failedQueue = []
}

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    console.log('收到响应:', response.status, response.config.url, response.data)
    // 直接返回数据
    return response.data
  },
  async (error) => {
    console.error('响应错误:', error)

    const { response, config } = error
    const userStore = useUserStore()

    if (response) {
      switch (response.status) {
        case 401: {
          // 如果是刷新token的请求失败，直接登出
          if (config.url.includes('/auth/refresh/')) {
            userStore.logout()
            router.push('/login')
            ElMessage.error('登录已过期，请重新登录')
            return Promise.reject(error)
          }

          // 如果有refresh token，尝试刷新
          if (userStore.refreshToken && !isRefreshing) {
            isRefreshing = true

            try {
              const response = await refreshTokenApi(userStore.refreshToken)
              if (response.success) {
                // 更新token
                userStore.token = response.data.access_token
                localStorage.setItem('token', response.data.access_token)

                // 处理队列中的请求
                processQueue(null, response.data.access_token)

                // 重试原请求
                config.headers.Authorization = `Bearer ${response.data.access_token}`
                return request(config)
              } else {
                throw new Error('刷新token失败')
              }
            } catch (refreshError) {
              console.error('刷新token失败:', refreshError)
              processQueue(refreshError, null)
              userStore.logout()
              router.push('/login')
              ElMessage.error('登录已过期，请重新登录')
              return Promise.reject(refreshError)
            } finally {
              isRefreshing = false
            }
          } else if (isRefreshing) {
            // 如果正在刷新token，将请求加入队列
            return new Promise((resolve, reject) => {
              failedQueue.push({ resolve, reject })
            }).then(token => {
              config.headers.Authorization = `Bearer ${token}`
              return request(config)
            }).catch(err => {
              return Promise.reject(err)
            })
          } else {
            // 没有refresh token，直接登出
            userStore.logout()
            router.push('/login')
            ElMessage.error('登录已过期，请重新登录')
          }
          break
        }
        case 403:
          ElMessage.error('没有权限访问该资源')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(response.data?.message || '请求失败')
      }
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }

    return Promise.reject(error)
  }
)

export default request
